package com.weituotian.controller;

import com.weituotian.common.controller.BaseController;
import com.weituotian.common.exception.ControllerException;
import com.weituotian.common.exception.ServiceException;
import com.weituotian.common.result.Option;
import com.weituotian.common.utils.PageInfo;
import com.weituotian.model.Role;
import com.weituotian.model.User;
import com.weituotian.service.IRoleService;
import com.weituotian.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 用户控制器
 */
@Controller("userController")
@RequestMapping("/user")
public class UserController extends BaseController {

    private final IUserService userService;

    private final IRoleService roleService;

    @Autowired
    public UserController(IUserService userService, IRoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }


    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }

    /**
     * 用户列表
     *
     * @param page 当前页数
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(String search_name, Integer page, Integer pagesize, Model model) {
        PageInfo<User> pageInfo = new PageInfo<User>(page, 4);

        //搜索条件
        Map<String, Object> condition = new HashMap<String, Object>();
        if (search_name != null) {
            if (StringUtils.isNoneBlank(search_name)) {
                condition.put("search_name", search_name);
            }
        }
        pageInfo.setCondition(condition);

        //查询用户列表,结果都保存在pageinfo里面了
        userService.getList(pageInfo);


        //ModelAndView mv = new ModelAndView();
        //mv.setViewName("user/tables");//设置返回模板名称
        //mv.addObject("user", users);//设置参数值，在前台页面可以通过获取到

        //返回视图
        model.addAttribute("pageinfo", pageInfo);

        model.addAttribute("edit_url", this.getContextPath() + "/user/edit");
        model.addAttribute("add_url", this.getContextPath() + "/user/add");
        model.addAttribute("delete_url", this.getContextPath() + "/user/delete");

//        model.addAttribute("cur_url", makeUrl());
        model.addAttribute("pageName", "用户列表");
        return "user/index";
    }

    /**
     * 增加页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/add")
    public String add(Model model) {
        User user = new User();

        model.addAttribute("user", user);
        model.addAttribute("openStatus", userService.getOpenStatus());

        model.addAttribute("form_url", this.getContextPath() + "/user/doadd");
        model.addAttribute("action", "add");
        model.addAttribute("pageName", "用户新增");


        return "user/edit";
    }

    /**
     * 处理增加用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/doadd", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doadd(User user) {
        //日期
        user.setCreatedate(new Date());

        //密码
        String pwd = user.getPassword();
        if (pwd != null && !StringUtils.isBlank(pwd)) {
            user.setPassword(DigestUtils.md5Hex(pwd));//md5密码加密
        }

        try {
            userService.add(user);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("增加成功!");
    }

    /**
     * 编辑页面
     *
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Integer id, Model model) {
        User user = userService.findById(id);

        //返回视图
        model.addAttribute("user", user);
        model.addAttribute("openStatus", userService.getOpenStatus());

        model.addAttribute("form_url", this.getContextPath() + "/user/doedit");
        model.addAttribute("action", "edit");
        model.addAttribute("pageName", "用户编辑");
        return "user/edit";
    }

    /**
     * 处理编辑
     *
     * @return
     */
    @RequestMapping(value = "/doedit", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doedit(User user) {
        User user2 = userService.findUserByLoginName(user.getLoginname());
        if (user2 != null && !user.getId().equals(user2.getId())) {
            return renderError("用户名已存在!");
        }

        //密码处理
        String pwd = user.getPassword();
        if (pwd != null && !StringUtils.isBlank(pwd)) {
            user.setPassword(DigestUtils.md5Hex(pwd));//md5密码加密
        } else {
            user.setPassword(null);
        }

        try {
            //更新用户,封装到了一个事务中
            userService.update(user);
        } catch (ServiceException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("修改成功！");
    }

    /**
     * 用户分配角色
     *
     * @return
     */
    @RequestMapping(value = "/grant")
    public Object grant(Integer id, Model model) throws ControllerException {

        User user = userService.findById(id);
        if (user == null) {
            throw new ControllerException("没有这个用户");
        }

        //本用户的所有角色
        List<Integer> userRoleIds = roleService.findRoleIdListByUserId(id);

        //所有角色列表,用于用户分配角色
        List<Role> roles = roleService.getAllRoleList();

        //生成option,将返回到视图
        List<Option> options = new ArrayList<Option>();
        for (Role role : roles) {
            Option option = new Option();
            option.setValue(role.getId().toString());
            option.setName(role.getName());
            String selected = "";//是否选中
            for (Integer uRoleId : userRoleIds) {
                //如果有id
                if (role.getId().equals(uRoleId)) {
                    selected = "checked";//设置选中
                    break;
                }
            }
            option.setSelected(selected);
            options.add(option);
        }

        model.addAttribute("roleOptions", options);


        model.addAttribute("pageName", "用户分配角色");
        model.addAttribute("grant_url", getContextPath() + "/user/dogrant");
        model.addAttribute("user", user);

        return "user/grant";
    }

    /**
     * 处理角色分配资源
     *
     * @return
     */
    @RequestMapping(value = "/dogrant", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object dogrant(Integer userId, @RequestParam(value = "roleIds[]", required = false) Integer[] roleIds) {
        try {
            userService.updateRoles(userId, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("分配失败!");
        }
        return renderSuccess("分配成功!");
    }

    /**
     * 批量删除
     *
     * @param id id
     * @return
     */
    @RequestMapping(value = "/delete", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") Integer[] ids) {
        try {
            userService.deleteByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("删除成功!");
    }
}
